package com.lottery.ruok.lottrey.activity;

import android.animation.Animator;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.NewLotteryDetailAdapter;
import com.lottery.ruok.lottrey.adapter.PrizeListAdapter;
import com.lottery.ruok.lottrey.adapter.ResultsAdapter;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.AddBetList;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.eventbusObject.ChangePlayType;
import com.lottery.ruok.lottrey.eventbusObject.GetAccountWithPush;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.eventbusObject.PrizePushInfo;
import com.lottery.ruok.lottrey.eventbusObject.StartPrzePush;
import com.lottery.ruok.lottrey.fragment.LotteryChangeTypeFragment;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetChatRoomCurrentStatus;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCurrentIssueNoRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetLotteryDetailRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetPrizeHistoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ChatRoomStatus;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCurrentIssueNoResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetLotteryDetailResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetPrizeHistroyResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.ui.BottomOrderLayout;
import com.lottery.ruok.lottrey.ui.component.BuyLotteryTopView;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.nex3z.flowlayout.FlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import count_down.CountDownManager;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import ui.AreaCircle;
import ui.GridSpacingItemDecoration;
import ui.IToastBellTip;
import utils.StringUtils;
import utils.Utils;

//import ui.IToastBell;

/*
 * 官方彩票投注大厅详情页
 * */

public class OfficalLotteryDetailActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener, SensorEventListener {
    private static final int WHAT_REFRESH_TIME = 10;
    SensorManager mSensorManager;
    @BindView(R.id.anim_view)
    LottieAnimationView animView;
    @BindView(R.id.anim_prize)
    LottieAnimationView animPrize;
    @BindView(R.id.shadow)
    ImageView shadow;
    @BindView(R.id.issue)
    TextView issue;
    @BindView(R.id.downtime)
    TextView downtime;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.listview)
    ListView listView;
    @BindView(R.id.check1)
    CheckBox check1;
    @BindView(R.id.check2)
    CheckBox check2;
    @BindView(R.id.check3)
    CheckBox check3;
    @BindView(R.id.check4)
    CheckBox check4;
    @BindView(R.id.check5)
    CheckBox check5;
    @BindView(R.id.checkbox)
    LinearLayout checkbox;
    @BindView(R.id.input_container)
    FlowLayout inputContainer;
    @BindView(R.id.input_ok)
    ImageView inputOk;
    @BindView(R.id.input)
    LinearLayout input;
    @BindView(R.id.webview)
    WebView webView;
    @BindView(R.id.start_prize)
    LinearLayout startPrize;
    @BindView(R.id.prize_list)
    ListView prizeList;
    @BindView(R.id.chooseballs)
    RecyclerView chooseballs;
    @BindView(R.id.ball_view)
    ImageView ball_view;
    @BindView(R.id.method_name)
    TextView method_name;
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.view_refresh_animation)
    LottieAnimationView viewRefreshAnimation;
    @BindView(R.id.view_refresh)
    FrameLayout viewRefresh;
    @BindView(R.id.buy_lottery_top)
    BuyLotteryTopView buyLotteryTop;
    @BindView(R.id.dice_gif_layout)
    LinearLayout dice_gif_layout;
    private int sign = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_REFRESH_TIME:
                    ivRefresh.setEnabled(true);
                    ivRefresh.setSelected(true);

                    break;
            }
        }
    };

    public ArrayList<ArrayList<Boolean>> chosenItems;
    private String results;
    private String checkBoxString = "";
    private ArrayList<EditText> edittextLists = new ArrayList();
    private int chooseCount;//选择的注数
    private String editTextString;
    private ResultsAdapter resultsAdapter;
    private ArrayList<String> bottomResultsList = new ArrayList<>();
    private String currentNo;
    private NewLotteryDetailAdapter myAdapter;
    private boolean mIsPrizeTime;//是否处于开奖状态
    private Vibrator mVibrator;//手机震动
    private boolean isShake = false;//记录摇动状态
    private MyHandler mHandler;
    private static final int START_SHAKE = 0x1;
    private static final int AGAIN_SHAKE = 0x2;
    private static final int END_SHAKE = 0x3;
    public String ANALYTIC_VERSION = "1.0";
    public GetLotteryDetailResponse getLotteryDetailResponse;
    public int typePosition1;
    public int typePosition2;
    public int typePosition3;
    private BottomOrderLayout mBottomOrderLayout;
    private LinkedHashMap recordLinkedHashMap;
    private PrizeListAdapter prizeListAdapter;
    private ArrayList<GetPrizeHistroyResponse> getPrizeHistroyResponses = new ArrayList<>();
    private CountDownManager.CountDownModel countDownModel;
    private GetCurrentIssueNoResponse data;
    private String lotteryCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_activity_lottery_detail);
        lotteryCode = getIntent().getStringExtra("code");
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        init();
        countDown();
        if (Utils.isEmpty(UserInfo.getToken())) {
            //未登录
            viewRefresh.setVisibility(View.GONE);
            viewRefresh.setSelected(false);
        } else {
            viewRefresh.setVisibility(View.VISIBLE);
            viewRefresh.setSelected(true);
        }

        buyLotteryTop.setBuyLotteryTopViewListener(new BuyLotteryTopView.BuyLotteryTopViewListener() {
            @Override
            public void tabOnClick(int type) {
                switch (type) {
                    //1back，2彩票名称，3投注记录，4走势，5规则
                    case 1:
                        finish();
                        break;
                    case 2:
                        ChooseLotteryActivity.startActivity(OfficalLotteryDetailActivity.this, getIntent().getStringExtra("code"));
                        break;
                    case 3:
                        gotoOrderList();
                        break;
                    case 4:
                        gotoPrizeList();
                        break;
                    case 5:
                        gotoRule();
                        break;

                }
            }
        });

        getRoomStatus();
        if (UserInfo.getChatStatus() == ChatRoomStatus.CHAT_ROOM_STATUS_OPEN) {
            ball_view.setVisibility(View.VISIBLE);
        } else if (UserInfo.getChatStatus() == ChatRoomStatus.CHAT_ROOM_STATUS_CLOSE) {
            ball_view.setVisibility(View.GONE);
        }
    }

    private void countDown() {
        countDownModel = new CountDownManager.CountDownModel() {
            @Override
            public void onExecute() {
                if (data != null) {
                    data.setTime(data.getTime() - 1);
                    if (data.getTime() >= 0) {
                        downtime.setText(Utils.getCountTimeByLong(data.getTime() * 1000));
                    } else {
                        if (!mIsPrizeTime) {
                            mIsPrizeTime = true;
                            GetPrizeHistroyResponse item = new GetPrizeHistroyResponse();
                            item.setIssue_no(currentNo);
                            item.setPrize_num("");
                            getPrizeHistroyResponses.add(0, item);
                            handlePrizeData();
                            setTimer();
                            setPrizeState();
                        }

                    }
                }
            }
        };


        CountDownManager.asInstance().register(countDownModel);

    }

    @Override
    protected void onDestroy() {
        CountDownManager.asInstance().unRegister(countDownModel);

        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    @JavascriptInterface
    public void count(final int count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                chooseCount = count;

                setMoney();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        mBottomOrderLayout.setLoginState();

        getRedPacketNum(ball_view);
        if (Utils.isEmpty(UserInfo.getToken())) {
            //未登录
            viewRefresh.setVisibility(View.GONE);
            viewRefresh.setSelected(false);
        } else {
            viewRefresh.setVisibility(View.VISIBLE);
            viewRefresh.setSelected(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrizePushInfo event) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        if (event.getCode() != null && getIntent().getStringExtra("code") != null) {
            if (event.getCode().equals(getIntent().getStringExtra("code"))) {
                if (event.getIssueNo() != null) {
                    if (getPrizeHistroyResponses.size() > 0 && Utils.isEmpty(getPrizeHistroyResponses.get(0).getPrize_num())) {
                        getPrizeHistroyResponses.get(0).setIssue_no(event.getIssueNo());
                        getPrizeHistroyResponses.get(0).setPrize_num(event.getPrizeNum());
                        handlePrizeData();
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetAccountWithPush getAccountWithPush) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        mBottomOrderLayout.setLoginState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartPrzePush event) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        setTimer();
        getPrizeHistory();
    }

    private void init() {
        initPrizeAnimal();
        getRedPacketNum(ball_view);

        Disposable observer = BetListActivity.results.getObservable().subscribe(new Consumer<ArrayList<BetListActivity.Result>>() {
            @Override
            public void accept(final ArrayList<BetListActivity.Result> results) {
                mBottomOrderLayout.getInclude_note_count().setText(results.size() + "");
            }
        });
        disposables.add(observer);

        initBottomLayout();
        mHandler = new MyHandler(this);
        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        int span_count = 14;
        GridLayoutManager ms = new GridLayoutManager(OfficalLotteryDetailActivity.this, span_count);
        chooseballs.setLayoutManager(ms);
        resultsAdapter = new ResultsAdapter(bottomResultsList, getIntent().getStringExtra("code"));
        int spacing = Utils.dip2px(OfficalLotteryDetailActivity.this, 4);
        boolean includeEdge = false;
        chooseballs.addItemDecoration(new GridSpacingItemDecoration(span_count, spacing, includeEdge));
        chooseballs.setAdapter(resultsAdapter);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/count.html");
        webView.addJavascriptInterface(this, "MyCount");

        getLotteryDetail(true);

        setTimer();

        getPrizeHistory();
    }

    private void initPrizeAnimal() {
        if (Common.isOfficialK3(lotteryCode)) {
            animPrize.setVisibility(View.GONE);
            for (int i = 0; i < 3; i++) {
                ImageView dice = new ImageView(this);
                Glide.with(this).load(R.drawable.dice).asGif().into(dice);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(this, 25), Utils.dip2px(this, 25));
                layoutParams.rightMargin = Utils.dip2px(this, 11);
                dice.setLayoutParams(layoutParams);
                dice_gif_layout.addView(dice);
            }
            dice_gif_layout.setVisibility(View.VISIBLE);
        } else {
            dice_gif_layout.setVisibility(View.GONE);
            animPrize.setVisibility(View.VISIBLE);
        }
    }

    private void getLotteryDetail(final boolean progress) {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(GetLotteryDetailRequest.class).getResult(getIntent().getStringExtra("code"), UserInfo.getToken())
                .compose(RxHelper.<GetLotteryDetailResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetLotteryDetailResponse>(this) {


                    @Override
                    protected void _onNext(GetLotteryDetailResponse g) {
                        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
                            return;
                        }
                        getLotteryDetailResponse = g;

                        if (getLotteryDetailResponse != null && getLotteryDetailResponse.getRemaining_balance() != null) {
                            if (!UserInfo.getToken().equals("")) {
                                UserInfo.setAccount(getLotteryDetailResponse.getRemaining_balance());
                                mBottomOrderLayout.setLoginState();
                            }
                        }

                        dataInit();
                    }

                    @Override
                    protected boolean showDialog() {
                        return progress;
                    }
                });
        disposables.add(disposableObserver);
    }

    private void initBottomLayout() {
        mBottomOrderLayout = new BottomOrderLayout(this,
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        if (!Utils.isFastDoubleClick()) {
                            startShake();
                        }
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        setContent(false);
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        setMoney();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        buyAction(true);
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        gotoShoppingCar();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        buyAction(false);
                        return null;
                    }
                }, true,
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        setMoney();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        gotoLoginActivity();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                      //  gotoSummaryActivity();
                        startActivity(new Intent(OfficalLotteryDetailActivity.this, OrderActivity.class));
                        return null;
                    }
                });
    }


    private void setPrizeState() {
        if (prizeList.getVisibility() != View.VISIBLE) {
            container.setVisibility(View.GONE);
           /* animPrize.setVisibility(View.VISIBLE);
            animPrize.resumeAnimation();*/
            if (Common.isOfficialK3(lotteryCode)) {
                dice_gif_layout.setVisibility(View.VISIBLE);
            } else {
                animPrize.setVisibility(View.VISIBLE);
                animPrize.resumeAnimation();
            }
        }
        mIsPrizeTime = true;
    }

    private void handlePrizeData() {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        if (getPrizeHistroyResponses.size() > 0) {
            String[] p = getPrizeHistroyResponses.get(0).getPrize_num().split(",");
            if (p.length > 0 && !p[0].equals("")) {
                container.removeAllViews();
              /*  Observable.fromArray(p)
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) {
                                AreaCircle areaCircle = new AreaCircle(OfficalLotteryDetailActivity.this);
                                Common.setBallBackground(areaCircle, s, getIntent().getStringExtra("code"));

                                areaCircle.setText(s);
                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(OfficalLotteryDetailActivity.this, 20), Utils.dip2px(OfficalLotteryDetailActivity.this, 20));
                                layoutParams.rightMargin = Utils.dip2px(OfficalLotteryDetailActivity.this, 11);
                                areaCircle.setLayoutParams(layoutParams);
                                container.addView(areaCircle);
                            }
                        });*/
                for (String s : p) {
                    if (Common.isOfficialK3(lotteryCode)) {
                        ImageView dice = new ImageView(this);
                        dice.setImageResource(Common.getDiceDrawable(StringUtils.parseInt(s)));
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(this, 20), Utils.dip2px(this, 24));
                        layoutParams.rightMargin = Utils.dip2px(this, 11);
                        dice.setLayoutParams(layoutParams);
                        container.addView(dice);
                    } else {
                        AreaCircle areaCircle = new AreaCircle(OfficalLotteryDetailActivity.this);
                        Common.setBallBackground(areaCircle, s, lotteryCode);
                        areaCircle.setText(s);
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(OfficalLotteryDetailActivity.this, 24), Utils.dip2px(OfficalLotteryDetailActivity.this, 24));
                        layoutParams.rightMargin = Utils.dip2px(OfficalLotteryDetailActivity.this, 11);
                        areaCircle.setLayoutParams(layoutParams);
                        container.addView(areaCircle);
                    }

                }
                if (prizeList.getVisibility() != View.VISIBLE) {
                    container.setVisibility(View.VISIBLE);
                    /*animPrize.setVisibility(View.GONE);
                    animPrize.pauseAnimation();*/
                    if (Common.isOfficialK3(lotteryCode)) {
                        dice_gif_layout.setVisibility(View.GONE);
                    } else {
                        animPrize.setVisibility(View.GONE);
                        animPrize.pauseAnimation();
                    }
                }

                mIsPrizeTime = false;
            } else {
                setPrizeState();
            }
            if (prizeListAdapter == null) {
                prizeListAdapter = new PrizeListAdapter(getPrizeHistroyResponses, OfficalLotteryDetailActivity.this, getIntent().getStringExtra("code"), mIsPrizeTime);
                prizeList.setAdapter(prizeListAdapter);
            } else {
                prizeListAdapter.setData(getPrizeHistroyResponses, getIntent().getStringExtra("code"), mIsPrizeTime);
            }
        }
    }

    private void getPrizeHistory() {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(GetPrizeHistoryRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<ArrayList<GetPrizeHistroyResponse>>handleResultReConnection())
                .subscribeWith(new RxSubscribe<ArrayList<GetPrizeHistroyResponse>>(this) {

                    @Override
                    protected void _onNext(ArrayList<GetPrizeHistroyResponse> g) {
                        if (getPrizeHistroyResponses != null) {
                            getPrizeHistroyResponses.clear();
                            getPrizeHistroyResponses.addAll(g);
                        }

                        handlePrizeData();
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
        disposables.add(disposableObserver);
    }

    private void setTimer() {
        RetrofitBase.getRetrofit().create(GetCurrentIssueNoRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<GetCurrentIssueNoResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetCurrentIssueNoResponse>(this) {
                    @Override
                    protected void _onNext(final GetCurrentIssueNoResponse getCurrentIssueNoResponse) {
                        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
                            return;
                        }

                        if (getCurrentIssueNoResponse != null) {
                            data = getCurrentIssueNoResponse;
                            currentNo = getCurrentIssueNoResponse.getNo();


                            String year = Utils.toYear(System.currentTimeMillis());
                            if (!Utils.isEmpty(getCurrentIssueNoResponse.getNo()) && getCurrentIssueNoResponse.getNo().startsWith(year)) {
                                issue.setText("距" + getCurrentIssueNoResponse.getNo().substring(4) + "期开奖");
                            } else {
                                issue.setText("距" + getCurrentIssueNoResponse.getNo() + "期开奖");
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void dataInit() {
        labelA:
        for (int i = 0; i < getLotteryDetailResponse.getLayouts().size(); i++) {
            if (getLotteryDetailResponse.getLayouts().get(i).getSelected().equals("1")) {
                for (int j = 0; j < getLotteryDetailResponse.getLayouts().get(i).getChildren().size(); j++) {
                    if (getLotteryDetailResponse.getLayouts().get(i).getChildren().get(j).getSelected().equals("1")) {
                        for (int m = 0; m < getLotteryDetailResponse.getLayouts().get(i).getChildren().get(j).getChildren().size(); m++) {
                            if (getLotteryDetailResponse.getLayouts().get(i).getChildren().get(j).getChildren().get(m).getSelected().equals("1")) {
                                typePosition1 = i;
                                typePosition2 = j;
                                typePosition3 = m;

                                getLotteryDetailResponse.getLayouts().get(i).setSelecteds("1");
                                getLotteryDetailResponse.getLayouts().get(i).getChildren().get(j).setSelecteds("1");
                                getLotteryDetailResponse.getLayouts().get(i).getChildren().get(j).getChildren().get(m).setSelecteds("1");
                                break labelA;
                            }
                        }
                    }
                }
            }
        }

        initBottomSLider();

        setTitle();

        setContent(true);
    }

    private void initBottomSLider() {//只有初始化和切换玩法的时候才将滑动条状态置为初始状态
        mBottomOrderLayout.initSlide(Float.parseFloat(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMin_rakeback()),
                Float.parseFloat(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_rakeback()),
                getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_profit(),
                getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMin_profit(),
                getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getTheory_odds(),
                getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_odds(),
                getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code(),
                getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getStatus2());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChangePlayType event) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        sign = event.getSign();
        initBottomSLider();

        setContent(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(AddBetSuccess addBetSuccess) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        if (addBetSuccess.getAfter_amount() != null) {
            UserInfo.setAccount(addBetSuccess.getAfter_amount());
            mBottomOrderLayout.setLoginState();
        } else {
            updateAccount(new AfterUpdateAccount() {
                @Override
                public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                    UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                    mBottomOrderLayout.setLoginState();
                }
            });
        }

//        Intent intent = new Intent(OfficalLotteryDetailActivity.this, OrderActivity.class);
//        intent.putExtra("from_buy", true);
//        startActivity(intent);
    }

    private void setOkCondition() {
        boolean isOk = true;
        for (EditText editText : edittextLists) {
            String s = editText.getText().toString();
            if (s.equals("") || !Utils.isNumeric(s)) {//如果广东11选5和北京pk10的话，必须一个框里要有两个数才能下注
                if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                    if (editText.getText().toString().length() < 2) {
                        isOk = false;
                        break;
                    }
                } else {
                    isOk = false;
                    break;
                }
            } else {
                if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                    if (editText.getText().toString().length() < 2) {
                        isOk = false;
                        break;
                    }
                }
            }
        }

        //checkbox检验
        if (getLotteryDetailResponse.getLayouts().size() > typePosition1
                && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().size() > typePosition2
                && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().size() > typePosition3) {
            if (!(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs() == null || getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs().size() == 0)) {
                if (getCheckNum() < Integer.parseInt(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row())) {
                    isOk = false;
                }
            }
        }

        if (isOk) {
            inputOk.setImageResource(R.mipmap.bigok);
            inputOk.setEnabled(true);
        } else {
            inputOk.setImageResource(R.mipmap.bigok_gray);
            inputOk.setEnabled(false);
        }
    }

    private void setContent(boolean initSlider) {
        bottomResultsList.clear();
        resultsAdapter.notifyDataSetChanged();

        editTextString = null;

        inputOk.setImageResource(R.mipmap.bigok_gray);
        inputOk.setEnabled(false);

        edittextLists.clear();

        checkBoxString = "";
        results = null;

        if (chosenItems != null) {
            chosenItems.clear();
        }

        chooseCount = 0;
        setMoney();

        if (getLotteryDetailResponse != null) {
            if (getLotteryDetailResponse.getLayouts().size() > typePosition1
                    && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().size() > typePosition2
                    && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().size() > typePosition3) {
                mBottomOrderLayout.setRefreshOdds(new Function1<ArrayList<String>, Unit>() {
                    @Override
                    public Unit invoke(ArrayList<String> strings) {
                        if (myAdapter != null && strings != null) {
                            recordLinkedHashMap = new LinkedHashMap(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_odds());
                            int array_index = 0;
                            for (Object key : recordLinkedHashMap.keySet()) {
                                recordLinkedHashMap.put(key, strings.get(array_index));
                                array_index++;
                            }
                            myAdapter.setDatas("hezhi_hezhi_hezhi", recordLinkedHashMap);
                            myAdapter.notifyDataSetChanged();
                        }
                        return null;
                    }
                });
                method_name.setText(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getName() + "-" + getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getName());
                if (!getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getInput().equals("1")) {
                    listView.setVisibility(View.VISIBLE);
                    input.setVisibility(View.GONE);

                    chosenItems = new ArrayList();

                    ItemsInit();

                    if (myAdapter == null) {
                        if (!initSlider && "hezhi_hezhi_hezhi".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {

                        } else {
                            recordLinkedHashMap = getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_odds();
                        }
                        myAdapter = new NewLotteryDetailAdapter(this, getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code(), recordLinkedHashMap);
                        listView.setAdapter(myAdapter);
                    } else {
                        if (!initSlider && "hezhi_hezhi_hezhi".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {

                        } else {
                            recordLinkedHashMap = getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_odds();
                        }
                        myAdapter.setDatas(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code(), recordLinkedHashMap);
                        myAdapter.notifyDataSetChanged();
                    }

                    listView.setVisibility(View.VISIBLE);
                } else {
                    if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {//每个方格填写两位数，所以特别在这里加提示
                        Utils.showToast("每个方格请填写两位数");
                    }

                    listView.setVisibility(View.GONE);
                    input.setVisibility(View.VISIBLE);

                    inputContainer.removeViews(0, inputContainer.getChildCount() - 1);
                    for (int i = 0; i < Integer.parseInt(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row()); i++) {
                        EditText v = (EditText) getLayoutInflater().inflate(R.layout.lottery_input_area, null);
                        if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                            int maxLength = 2;
                            InputFilter[] fArray = new InputFilter[1];
                            fArray[0] = new InputFilter.LengthFilter(maxLength);
                            v.setFilters(fArray);
                        }
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(this, 42), Utils.dip2px(this, 50));
                        if (i < Integer.parseInt(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row()) - 1) {
                            layoutParams.rightMargin = Utils.dip2px(this, 17);
                        }
                        v.setLayoutParams(layoutParams);
                        inputContainer.addView(v, inputContainer.getChildCount() - 1);
                        edittextLists.add(v);
                    }
                    for (int i = 0; i < Integer.parseInt(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row()); i++) {
                        final int index = i;

                        edittextLists.get(i).addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                            }

                            @Override
                            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                            }

                            @Override
                            public void afterTextChanged(Editable editable) {
                                setOkCondition();

                                if (index + 1 < Integer.parseInt(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row())) {
                                    int len = 1;
                                    if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                                        len = 2;
                                    }
                                    if (editable.length() >= len) {
                                        if (edittextLists.get(index + 1).length() == 0) {
                                            edittextLists.get(index + 1).requestFocus();
                                        }
                                    }
                                }

                                if (index > 0) {
                                    if (editable.length() == 0) {
                                        edittextLists.get(index - 1).requestFocus();
                                    }
                                }
                            }
                        });
                    }
                }

                if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs() == null || getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs().size() == 0) {
                    checkbox.setVisibility(View.GONE);
                } else {
                    checkbox.setVisibility(View.VISIBLE);

                    check1.setChecked(false);
                    check2.setChecked(false);
                    check3.setChecked(false);
                    check4.setChecked(false);
                    check5.setChecked(false);

                    check1.setOnCheckedChangeListener(this);
                    check2.setOnCheckedChangeListener(this);
                    check3.setOnCheckedChangeListener(this);
                    check4.setOnCheckedChangeListener(this);
                    check5.setOnCheckedChangeListener(this);
                }
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        listenToChange();

        setOkCondition();
    }

    private int getCheckNum() {
        int num = 0;
        checkBoxString = "";
        if (check1.isChecked()) {
            if (checkBoxString.equals("")) {
                checkBoxString = check1.getText().toString();
            } else {
                checkBoxString += "," + check1.getText().toString();
            }
            num++;
        }
        if (check2.isChecked()) {
            if (checkBoxString.equals("")) {
                checkBoxString = check2.getText().toString();
            } else {
                checkBoxString += "," + check2.getText().toString();
            }
            num++;
        }
        if (check3.isChecked()) {
            if (checkBoxString.equals("")) {
                checkBoxString = check3.getText().toString();
            } else {
                checkBoxString += "," + check3.getText().toString();
            }
            num++;
        }
        if (check4.isChecked()) {
            if (checkBoxString.equals("")) {
                checkBoxString = check4.getText().toString();
            } else {
                checkBoxString += "," + check4.getText().toString();
            }
            num++;
        }
        if (check5.isChecked()) {
            if (checkBoxString.equals("")) {
                checkBoxString = check5.getText().toString();
            } else {
                checkBoxString += "," + check5.getText().toString();
            }
            num++;
        }
        return num;
    }

    private void setMoney() {
        if (chooseCount > 0) {
            mBottomOrderLayout.bottomShowState2();
        } else {
            mBottomOrderLayout.bottomShowState1();
        }
        mBottomOrderLayout.getNumAndMoney().setText(chooseCount + "注" + Utils.saveTwoFormat(chooseCount * mBottomOrderLayout.returnMoney() * mBottomOrderLayout.returnUnit()) + "元");
    }

    public void specialHandle(int row, int column) {
        String code = getIntent().getStringExtra("code");
        if ("ahk3".equals(code) || "jiangsuk3".equals(code)) {
            if (getLotteryDetailResponse.getLayouts().size() > typePosition1
                    && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().size() > typePosition2
                    && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().size() > typePosition3) {
                if ("santonghao_santonghaotongxuan_santonghaotongxuan".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {
                    boolean ahk3Change = false;
                    if (chosenItems.get(row).get(column)) {
                        ahk3Change = true;
                    }
                    for (ArrayList<Boolean> chsItem : chosenItems) {
                        for (int i = 0; i < chsItem.size(); i++) {
                            chsItem.set(i, ahk3Change);
                        }
                    }
                    if (myAdapter != null) {
                        myAdapter.notifyDataSetChanged();
                    }
                }
                if ("ertonghao_ertonghaodanxuan_biaozhunxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())
                        || "erbutonghao_erbutonghao_dantuoxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {
                    if (row == 0) {
                        if (column < chosenItems.get(row).size()) {
                            if (chosenItems.get(row).get(column)) {
                                if (chosenItems.size() >= 2) {
                                    chosenItems.get(1).set(column, false);
                                    for (int i = 0; i < chosenItems.get(row).size(); i++) {
                                        if (i != column) {
                                            chosenItems.get(row).set(i, false);
                                        }
                                    }
                                    if (myAdapter != null) {
                                        myAdapter.notifyDataSetChanged();
                                    }
                                }
                            }
                        }
                    } else if (row == 1) {
                        if (column < chosenItems.get(row).size()) {
                            if (chosenItems.get(row).get(column)) {
                                if (chosenItems.size() > 0) {
                                    chosenItems.get(0).set(column, false);
                                    if (myAdapter != null) {
                                        myAdapter.notifyDataSetChanged();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public synchronized void listenToChange() {
        if (getLotteryDetailResponse != null
                && getLotteryDetailResponse.getLayouts() != null
                && getLotteryDetailResponse.getLayouts().size() > typePosition1
                && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren() != null
                && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().size() > typePosition2
                && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren() != null
                && getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().size() > typePosition3) {
            results = null;
            String numberRepeat = getLotteryDetailResponse.getNumber_repeat();
            String checkNum = getCheckNum() + "";
            JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("need_row", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row());
                jsonObject.put("need_number", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_number());
                jsonObject.put("multiple", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMultiple());
                jsonObject.put("input", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getInput());
                if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNotes() != null) {
                    jsonObject.put("notes", new JSONObject(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNotes()));
                } else {
                    jsonObject.put("notes", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNotes());
                }
                jsonObject.put("checkboxs", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs());
                if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")) {
                    jsonObject.put("is_special", 1);
                } else {
                    jsonObject.put("is_special", 0);
                }
                jsonObject.put("layout_code", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            bottomResultsList.clear();
            ArrayList<Integer> arrayList = new ArrayList();
            ArrayList<String> arrayList1 = new ArrayList();
            for (int i = 0; i < chosenItems.size(); i++) {
                Integer integer = 0;
                StringBuilder re = new StringBuilder("");
                for (int j = 0; j < chosenItems.get(i).size(); j++) {
                    if (chosenItems.get(i).get(j)) {
                        integer++;

                        arrayList1.add(i + "" + j);

                        if (!re.toString().equals("")) {
                            re.append(",").append(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects().get(i).getContent().get(j));
                        } else {
                            re = new StringBuilder(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects().get(i).getContent().get(j));
                        }
                    }
                }
                if (results == null) {
                    results = re.toString();
                } else {
                    results = results + "|" + re;
                }
                if (integer != 0) {
                    arrayList.add(integer);
                }
            }

            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayList.size(); i++) {
                jsonArray.put(arrayList.get(i).intValue());
            }
            JSONArray jsonArray1 = new JSONArray();

            if (!getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getInput().equals("1")) {
                for (int i = 0; i < arrayList1.size(); i++) {
                    jsonArray1.put(arrayList1.get(i));
                }
            } else {
                if (editTextString != null) {
                    String[] rows = editTextString.split(",");
                    for (String row : rows) {
                        jsonArray1.put(row);
                        if (getIntent().getStringExtra("code").equals("bjpk10") || getIntent().getStringExtra("code").equals("gd11x5")) {
                            String[] select_nums = row.split(" ");

                            if (bottomResultsList.size() > 0) {
                                bottomResultsList.add(",");
                            }

                            bottomResultsList.addAll(Arrays.asList(select_nums));
                        } else {
                            if (bottomResultsList.size() > 0) {
                                bottomResultsList.add(",");
                            }

                            for (int j = 0; j < row.length(); j++) {
                                if (!(row.charAt(j) + "").equals(" ")) {
                                    bottomResultsList.add(row.charAt(j) + "");
                                }
                            }
                        }

                        if (results == null) {
                            results = row;
                        } else {
                            if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getInput().equals("1")) {
                                results = results + "," + row;
                            } else {
                                results = results + "|" + row;
                            }
                        }
                    }
                }
            }
            resultsAdapter.notifyDataSetChanged();

            String t;
            if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code().equals("wuxing_wuxingzhixuan_zuhe")
                    || getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code().equals("housi_housizhixuan_zuhe")
                    || getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code().equals("qiansi_qiansizhixuan_zuhe")) {
                JSONObject jsonObjects = new JSONObject();
                try {
                    JSONArray jsonArrayWan = new JSONArray();
                    jsonObjects.put("万位", jsonArrayWan);

                    JSONArray jsonArrayQian = new JSONArray();
                    jsonObjects.put("千位", jsonArrayQian);

                    JSONArray jsonArrayBai = new JSONArray();
                    jsonObjects.put("百位", jsonArrayBai);

                    JSONArray jsonArrayShi = new JSONArray();
                    jsonObjects.put("十位", jsonArrayShi);

                    JSONArray jsonArrayGe = new JSONArray();
                    jsonObjects.put("个位", jsonArrayGe);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < jsonArray1.length(); i++) {
                    try {
                        String selectNums = jsonArray1.getString(i);

                        switch (selectNums.charAt(0)) {
                            case '0':
                                jsonObjects.getJSONArray("万位").put(selectNums.charAt(1) + "");
                                break;
                            case '1':
                                jsonObjects.getJSONArray("千位").put(selectNums.charAt(1) + "");
                                break;
                            case '2':
                                jsonObjects.getJSONArray("百位").put(selectNums.charAt(1) + "");
                                break;
                            case '3':
                                jsonObjects.getJSONArray("十位").put(selectNums.charAt(1) + "");
                                break;
                            case '4':
                                jsonObjects.getJSONArray("个位").put(selectNums.charAt(1) + "");
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    if (jsonObjects.getJSONArray("万位").length() == 0) {
                        jsonObjects.remove("万位");
                    } else if (jsonObjects.getJSONArray("千位").length() == 0) {
                        jsonObjects.remove("千位");
                    } else if (jsonObjects.getJSONArray("百位").length() == 0) {
                        jsonObjects.remove("百位");
                    } else if (jsonObjects.getJSONArray("十位").length() == 0) {
                        jsonObjects.remove("十位");
                    } else if (jsonObjects.getJSONArray("个位").length() == 0) {
                        jsonObjects.remove("个位");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t = jsonObject + "," + numberRepeat + "," + jsonObjects + "," + jsonArray + "," + checkNum;
            } else {
                t = jsonObject + "," + numberRepeat + "," + jsonArray1 + "," + jsonArray + "," + checkNum;
            }
            String func = "javascript:count_note(" + t + ")";
            webView.loadUrl(func);
        }
    }

    private void setTitle() {
        buyLotteryTop.setLotteryName(getLotteryDetailResponse.getName());
    }

    private void createOneBet() {
        setContent(false);//清空已经选择的数据

        if (getLotteryDetailResponse != null) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("need_row", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_row());
                jsonObject.put("need_number", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getNeed_number());
                jsonObject.put("multiple", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMultiple());
                jsonObject.put("input", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getInput());
                jsonObject.put("notes", "{}");
                jsonObject.put("checkboxs", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs());
                jsonObject.put("rule_id", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getRule_id());
                if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects() != null) {
                    JSONArray jsonArray = new JSONArray();
                    for (GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX.ChildrenBean.SelectsBean selectsBean : getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects()) {
                        JSONObject jsonObject1 = new JSONObject();
                        JSONArray jsonArray1 = new JSONArray(selectsBean.getContent());
                        jsonObject1.put("content", jsonArray1);
                        jsonArray.put(jsonObject1);
                    }
                    jsonObject.put("selects", jsonArray.toString());
                } else {
                    jsonObject.put("selects", "{}");
                }
                jsonObject.put("layout_code", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code());
                jsonObject.put("item_code", getIntent().getStringExtra("code"));
            } catch (Exception e) {
                e.printStackTrace();
            }

            String t = jsonObject + "," + getLotteryDetailResponse.getNumber_repeat() + "," + getLotteryDetailResponse.getNumber_format() + ",'" + getLotteryDetailResponse.getNumber_range() + "'";
            String func = "javascript:generate_item(" + t + ")";
            webView.loadUrl(func);
        }
    }

    @JavascriptInterface
    public void getRandomString(final String notes, final int counts) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {//手写没有逗号隔开，选择则是逗号
                if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getInput().equals("1")) {
                    editTextString = notes;
                    String code = getIntent().getStringExtra("code");
                    if ("ahk3".equals(code) || "jiangsuk3".equals(code)) {
                        if ("ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {
                            //取前两个字符，并把第一个字符复制一遍
                            editTextString = editTextString.charAt(0) + editTextString;
                            editTextString = editTextString.substring(0, editTextString.length() - 1);
                        }
                    }
                    listenToChange();
                } else {//竖线隔开是行，逗号隔开在一个行里。
                    String[] rows = notes.split("\\|", -1);//分割出来结果是"|"和""的时候表示这一行还没有选择
                    int temp = 0;
                    int current = 0;
                    for (int i = 0; i < rows.length; i++) {
                        if (!rows[i].equals("") && !rows[i].equals("|")) {
                            String[] indexs = rows[i].split(",");
                            for (String index : indexs) {
                                int position = getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects().get(i).getContent().indexOf(index);
                                if (position != -1) {
                                    chosenItems.get(i).set(position, true);
                                    if (temp == 0) {
                                        current = i;
                                        temp++;
                                    }
                                }
                            }
                        }
                    }
                    if (myAdapter != null) {
                        myAdapter.notifyDataSetChanged();
                        listView.setSelection(current);
                    }

                    listenToChange();
                }

                if (getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getCheckboxs() != null) {
                    int notesLength;//随机选择长度为notesLength的checkboxs
                    if (notes.contains(",")) {
                        notesLength = notes.split(",").length;
                    } else {
                        notesLength = notes.length();
                    }
                    int[] a = new int[]{1, 2, 3, 4, 5};
                    if (sign == 1) {
                        Utils.combine(a, 3);
                    } else {
                        Utils.combine(a, notesLength);
                    }

                    if (Utils.results.size() > 0) {
                        int t = Utils.getRandom(0, Utils.results.size());
                        int[] checks = Utils.results.get(t);
                        for (int index : checks) {
                            switch (index) {
                                case 1:
                                    check1.setChecked(true);
                                    break;
                                case 2:
                                    check2.setChecked(true);
                                    break;
                                case 3:
                                    check3.setChecked(true);
                                    break;
                                case 4:
                                    check4.setChecked(true);
                                    break;
                                case 5:
                                    check5.setChecked(true);
                                    break;
                            }
                        }
                    }
                }
            }
        });
    }

    private void exitConfirm() {
        if (BetListActivity.results.size() > 0) {
            Utils.createDialog(this, "是否放弃所选号码", "是", "否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        int count = getSupportFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            exitConfirm();
        } else {
            getSupportFragmentManager().popBackStack();
        }
    }

    @Override
    public void finish() {
        super.finish();

        BetListActivity.results.clear();
    }

    private void buyAction(boolean gotoOrderList) {
        removeSoftKeyboard(findViewById(android.R.id.content));
        if (!UserInfo.getToken().equals("")) {
            if (chooseCount == 0) {
                IToastBellTip.show(OfficalLotteryDetailActivity.this);
            } else {
                if (!mBottomOrderLayout.getMoney_and_num().getText().toString().trim().equals("")) {
                    if (Utils.parseFloat(mBottomOrderLayout.getMoney_and_num().getText().toString().trim()) == 0) {
                        Utils.showToast("下注金额不能为0");
                        return;
                    }
                    if (chooseCount <= 2000) {
//                        if (chooseCount * mBottomOrderLayout.returnMoney() * mBottomOrderLayout.returnUnit() > Float.parseFloat(UserInfo.getAccount())) {
//                            Utils.showToast("您的余额不足");
//                        } else {
                            if (gotoOrderList) {
                                String code = getIntent().getStringExtra("code");
                                if ("ahk3".equals(code) || "jiangsuk3".equals(code)) {
                                    if ("ertonghao_ertonghaodanxuan_biaozhunxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {
                                        if (results != null) {
                                            results = results.substring(1, results.length());
                                        }
                                    }
                                }

                                Intent intent = new Intent(OfficalLotteryDetailActivity.this, BetListActivity.class);
                                intent.putExtra("status2", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getStatus2());
                                if (results != null) {
                                    intent.putExtra("result", results);
                                }
                                intent.putExtra("name", getLotteryDetailResponse.getLayouts().get(typePosition1).getName() + "-" + getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getName());
                                intent.putExtra("num", chooseCount);
                                intent.putExtra("money", mBottomOrderLayout.returnMoney() * mBottomOrderLayout.returnUnit() * chooseCount);
                                if (currentNo != null) {
                                    intent.putExtra("no", Long.parseLong(currentNo));
                                }
                                intent.putExtra("code", getIntent().getStringExtra("code"));
                                intent.putExtra("rule_id", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getRule_id());
                                intent.putExtra("checkBoxString", checkBoxString);
                                intent.putExtra("layout_code", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code());
                                intent.putExtra("rakeback", mBottomOrderLayout.getNow_rakeback());
                                StringBuilder now_odds = null;
                                for (int s = 0; s < mBottomOrderLayout.getOddNumber().size(); s++) {
                                    if (s == 0) {
                                        now_odds = new StringBuilder(mBottomOrderLayout.getOddNumber().get(s));
                                    } else {
                                        now_odds.append(",").append(mBottomOrderLayout.getOddNumber().get(s));
                                    }
                                }
                                intent.putExtra("odds", now_odds.toString());
                                intent.putExtra("amount_per_note", mBottomOrderLayout.returnMoney() * mBottomOrderLayout.returnUnit());
                                intent.putExtra("shopping_car", false);//是否是购物车逻辑进入
                                intent.putExtra("object", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3));
                                intent.putExtra("getNumber_format", getLotteryDetailResponse.getNumber_format());
                                intent.putExtra("getNumber_range", getLotteryDetailResponse.getNumber_range());
                                intent.putExtra("getNumber_repeat", getLotteryDetailResponse.getNumber_repeat());
                                Gson gson = new Gson();
                                String list1 = gson.toJson(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_odds());
                                String list2 = gson.toJson(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getTheory_odds());
                                intent.putExtra("max_rakeback", Float.parseFloat(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_rakeback()));
                                intent.putExtra("max_odds", list1);
                                intent.putExtra("theory_odds", list2);
                                intent.putExtra("max_profit", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_profit());
                                intent.putExtra("min_profit", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMin_profit());
                                intent.putExtra("min_rakeback", Float.parseFloat(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMin_rakeback()));
                                startActivity(intent);
                            } else {
                                String code = getIntent().getStringExtra("code");
                                if ("ahk3".equals(code) || "jiangsuk3".equals(code)) {
                                    if ("ertonghao_ertonghaodanxuan_biaozhunxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) {
                                        if (results != null) {
                                            results = results.substring(1, results.length());
                                        }
                                    }
                                }
                                StringBuilder now_odds = null;
                                for (int s = 0; s < mBottomOrderLayout.getOddNumber().size(); s++) {
                                    if (s == 0) {
                                        now_odds = new StringBuilder(mBottomOrderLayout.getOddNumber().get(s));
                                    } else {
                                        now_odds.append(",").append(mBottomOrderLayout.getOddNumber().get(s));
                                    }
                                }
                                Gson gson = new Gson();
                                String list1 = gson.toJson(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_odds());
                                String list2 = gson.toJson(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getTheory_odds());
                                BetListActivity.addOneNote(results,
                                        getLotteryDetailResponse.getLayouts().get(typePosition1).getName() + "-" + getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getName(),
                                        chooseCount,
                                        mBottomOrderLayout.returnMoney() * mBottomOrderLayout.returnUnit() * chooseCount,
                                        mBottomOrderLayout.returnMoney() * mBottomOrderLayout.returnUnit(),
                                        checkBoxString,
                                        getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getRule_id(),
                                        mBottomOrderLayout.getNow_rakeback(),
                                        now_odds.toString(),
                                        getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3),
                                        Float.parseFloat(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_rakeback()),
                                        list1,
                                        list2,
                                        getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMax_profit(),
                                        getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMin_profit(),
                                        Float.parseFloat(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getMin_rakeback()),
                                        getIntent().getStringExtra("code"),
                                        getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code());

                                setContent(false);
                                mBottomOrderLayout.bottomShowState1();
                            }
//                        }
                    } else {
                        Utils.showToast(Common.NUM_PER_NOTE);
                    }
                }
                else {
                    Utils.showToast("请填写金额");
                }
            }
        } else {
            gotoLoginActivity();
        }
    }

    private void gotoShoppingCar() {
        if (BetListActivity.results.size() > 0) {
            Intent intent = new Intent(OfficalLotteryDetailActivity.this, BetListActivity.class);
            intent.putExtra("code", getIntent().getStringExtra("code"));
            intent.putExtra("layout_code", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code());
            if (currentNo != null) {
                intent.putExtra("no", Long.parseLong(currentNo));
            }
            intent.putExtra("shopping_car", true);//是否是购物车逻辑进入
            startActivity(intent);
        } else {
            Utils.showToast("您还未添加注单");
        }
    }

    @OnClick({R.id.rl_play_method, R.id.input_ok, R.id.start_prize, R.id.ball_view, R.id.iv_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ball_view:
                gotoChatRoom(lotteryCode);
                break;
            case R.id.rl_play_method:
                LotteryChangeTypeFragment lotteryChangeTypeFragment = new LotteryChangeTypeFragment();
                if (lotteryChangeTypeFragment != null) {
                    lotteryChangeTypeFragment.setDatas(getLotteryDetailResponse);
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction ft = manager.beginTransaction();
                    ft.setCustomAnimations(R.anim.anim_enter_from_bottom, R.anim.anim_exit_from_bottom, R.anim.anim_enter_from_bottom, R.anim.anim_exit_from_bottom);
                    ft.replace(android.R.id.content, lotteryChangeTypeFragment);
                    ft.addToBackStack(null);
                    ft.commitAllowingStateLoss();
                }
                break;
            case R.id.input_ok:
                StringBuilder a = new StringBuilder("");
                HashSet<String> repetitions = new HashSet<>();
                String[] number_range = getLotteryDetailResponse.getNumber_range().split("-");
                for (EditText editText : edittextLists) {
                    if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")
                            || (getIntent().getStringExtra("code").equals("ahk3") && "erbutonghao_erbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                            || (getIntent().getStringExtra("code").equals("ahk3") && "ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                            || (getIntent().getStringExtra("code").equals("ahk3") && "sanbutonghao_sanbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                            || (getIntent().getStringExtra("code").equals("jiangsuk3") && "erbutonghao_erbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                            || (getIntent().getStringExtra("code").equals("jiangsuk3") && "ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                            || (getIntent().getStringExtra("code").equals("jiangsuk3") && "sanbutonghao_sanbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))) {//这种写法是为了适配这两种特殊玩法，北京pk10和广东11选5（后来添加安徽快三）
                        if (a.toString().equals("")) {
                            a.append(editText.getText().toString());
                        } else {
                            if (((getIntent().getStringExtra("code").equals("ahk3") && "erbutonghao_erbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) || (getIntent().getStringExtra("code").equals("ahk3") && "ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()) || (getIntent().getStringExtra("code").equals("ahk3") && "sanbutonghao_sanbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))))
                                    || ((getIntent().getStringExtra("code").equals("jiangsuk3") && "erbutonghao_erbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code())) || (getIntent().getStringExtra("code").equals("jiangsuk3") && "ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()) || (getIntent().getStringExtra("code").equals("jiangsuk3") && "sanbutonghao_sanbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))))
                                    ) {
                                a.append(editText.getText().toString());
                            } else {
                                a.append(" ").append(editText.getText().toString());
                            }
                        }
                        repetitions.add(Integer.parseInt(editText.getText().toString()) + "");

                        if (number_range != null && number_range.length == 2) {
                            if (Integer.parseInt(editText.getText().toString()) < Integer.parseInt(number_range[0]) || Integer.parseInt(editText.getText().toString()) > Integer.parseInt(number_range[1])) {
                                Utils.showToast("不能超出范围" + getLotteryDetailResponse.getNumber_range());
                                return;
                            }
                        }
                    } else {
                        a.append(editText.getText().toString());
                    }
                }
                if (getIntent().getStringExtra("code").equals("gd11x5") || getIntent().getStringExtra("code").equals("bjpk10")
                        || (getIntent().getStringExtra("code").equals("ahk3") && "erbutonghao_erbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                        || (getIntent().getStringExtra("code").equals("ahk3") && "sanbutonghao_sanbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                        || (getIntent().getStringExtra("code").equals("jiangsuk3") && "erbutonghao_erbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                        || (getIntent().getStringExtra("code").equals("jiangsuk3") && "sanbutonghao_sanbutonghao_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))

                        ) {//不能重复元素，不能超出范围，针对这些玩法
                    if (repetitions.size() != edittextLists.size()) {
                        Utils.showToast("不能选择重复数字");
                        return;
                    }
                }
                if ((getIntent().getStringExtra("code").equals("ahk3") && "ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                        || (getIntent().getStringExtra("code").equals("jiangsuk3") && "ertonghao_ertonghaodanxuan_shoudongxuanhao".equals(getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getLayout_code()))
                        ) {
                    if (repetitions.size() == edittextLists.size()) {
                        Utils.showToast("请选择两个相同球号和一个不同球号");
                        return;
                    } else if (repetitions.size() == 1) {
                        Utils.showToast("请选择两个相同球号和一个不同球号");
                        return;
                    }
                }

                if (editTextString == null) {
                    editTextString = a.toString();
                } else {
                    editTextString = editTextString + "," + a;
                }

                inputOk.setImageResource(R.mipmap.bigok_gray);
                inputOk.setEnabled(false);
                for (EditText editText : edittextLists) {
                    editText.setText("");
                }
                if (edittextLists.size() > 0) {
                    edittextLists.get(0).requestFocus();
                }

                listenToChange();
                break;
            case R.id.start_prize:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_recent_drawbtn");

                recentPrize();
                break;

            case R.id.iv_refresh:
                view.setEnabled(false);
                view.setSelected(false);
                view.setVisibility(View.GONE);
                handler.sendEmptyMessageDelayed(WHAT_REFRESH_TIME, 20000);
                viewRefreshAnimation.setVisibility(View.VISIBLE);
                viewRefreshAnimation.playAnimation();
                viewRefreshAnimation.addAnimatorListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        ivRefresh.setVisibility(View.VISIBLE);
                        viewRefreshAnimation.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {

                    }
                });
                updateAccount(new AfterUpdateAccount() {
                    @Override
                    public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                        UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                        mBottomOrderLayout.setLoginState();
                    }
                });
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(AddBetList addBetList) {
        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
            return;
        }
        setContent(false);
    }

    public void gotoOrderList() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_betrecord_jump");

        if (!UserInfo.getToken().equals("")) {
            //切换到第四个tab栏
            startActivity(new Intent(OfficalLotteryDetailActivity.this, OrderActivity.class));
        } else {
            gotoLoginActivity();
        }
    }

    public void gotoPrizeList() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_numdistributing_jump");

        Intent intent = new Intent(OfficalLotteryDetailActivity.this, PrizeListActivity.class);
        intent.putExtra("code", getIntent().getStringExtra("code"));
        intent.putExtra("isFromDetail", true);
        startActivity(intent);
    }

    public void recentPrize() {
        if (container.getVisibility() == View.VISIBLE || animPrize.getVisibility() == View.VISIBLE|| dice_gif_layout.getVisibility() == View.VISIBLE) {
//            shadow.setVisibility(View.VISIBLE);
            container.setVisibility(View.GONE);
            dice_gif_layout.setVisibility(View.GONE);
            animPrize.setVisibility(View.GONE);
            animPrize.pauseAnimation();

            prizeList.setVisibility(View.VISIBLE);
            animView.setAnimation("xia.json");
            animView.playAnimation();
        } else {
            if (mIsPrizeTime) {
                /*animPrize.setVisibility(View.VISIBLE);
                animPrize.resumeAnimation();*/
                if (Common.isOfficialK3(lotteryCode)) {
                    dice_gif_layout.setVisibility(View.VISIBLE);
                } else {
                    animPrize.setVisibility(View.VISIBLE);
                    animPrize.resumeAnimation();
                }
            } else {
                container.setVisibility(View.VISIBLE);
            }
//            shadow.setVisibility(View.GONE);

            prizeList.setVisibility(View.GONE);
            animView.setAnimation("shang.json");
            animView.playAnimation();
        }
    }

    public void gotoRule() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_lotteryrule_jump");

        Intent intent = new Intent(OfficalLotteryDetailActivity.this, PlayRuleActivity.class);
        intent.putExtra("code", getIntent().getStringExtra("code"));
        startActivity(intent);
    }

    public void gotoPlayTip() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_playmethod_jump");
        try {
            if (getLotteryDetailResponse != null) {
                Intent intent = new Intent(OfficalLotteryDetailActivity.this, PlayTipActivity.class);
                intent.putExtra("help", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getHelp());
                intent.putExtra("tips", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getTips());
                intent.putExtra("example", getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getExample());
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void ItemsInit() {
        chosenItems.clear();
        for (int i = 0; i < getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects().size(); i++) {
            ArrayList<Boolean> arrayList = new ArrayList();
            chosenItems.add(arrayList);
            for (int j = 0; j < getLotteryDetailResponse.getLayouts().get(typePosition1).getChildren().get(typePosition2).getChildren().get(typePosition3).getSelects().get(i).getContent().size(); j++) {
                arrayList.add(false);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
        if (mSensorManager != null) {
            Sensor mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            if (mAccelerometerSensor != null) {
                mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);
            }
        }
    }

    @Override
    protected void onPause() {
        // 务必要在pause中注销 mSensorManager
        // 否则会造成界面退出后摇一摇依旧生效的bug
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }

        super.onPause();
    }

    ///////////////////////////////////////////////////////////////////////////
    // 传感器开始
    ///////////////////////////////////////////////////////////////////////////

    static final int UPDATE_INTERVAL = 100;
    /**
     * 上一次检测的时间
     */
    long mLastUpdateTime;
    /**
     * 上一次检测时，加速度在x、y、z方向上的分量，用于和当前加速度比较求差。
     */
    float mLastX, mLastY, mLastZ;

    /**
     * 摇晃检测阈值，决定了对摇晃的敏感程度，越小越敏感。
     */
    public int shakeThreshold = 3500;

    @Override
    public void onSensorChanged(SensorEvent event) {
        int type = event.sensor.getType();

        if (type == Sensor.TYPE_ACCELEROMETER) {
            long currentTime = System.currentTimeMillis();
            long diffTime = currentTime - mLastUpdateTime;
            if (diffTime < UPDATE_INTERVAL) {
                return;
            }
            mLastUpdateTime = currentTime;
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];
            float deltaX = x - mLastX;
            float deltaY = y - mLastY;
            float deltaZ = z - mLastZ;
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            float delta = (float) (Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / diffTime * 10000);
            if (delta > shakeThreshold && !isShake) {// 当加速度的差值大于指定的阈值，认为这是一个摇晃
                startShake();
            }
        }
    }

    private void startShake() {
        if (mBottomOrderLayout.getInclude_state1().getVisibility() == View.VISIBLE) {
            isShake = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        mHandler.obtainMessage(START_SHAKE).sendToTarget();
                        Thread.sleep(500);
                        mHandler.obtainMessage(AGAIN_SHAKE).sendToTarget();
                        Thread.sleep(500);
                        mHandler.obtainMessage(END_SHAKE).sendToTarget();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
    }

    private static class MyHandler extends Handler {
        private WeakReference<OfficalLotteryDetailActivity> mReference;
        private OfficalLotteryDetailActivity mActivity;

        public MyHandler(OfficalLotteryDetailActivity activity) {
            mReference = new WeakReference(activity);
            if (mReference != null) {
                mActivity = mReference.get();
            }
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mActivity != null) {
                switch (msg.what) {
                    case START_SHAKE:
                        mActivity.mVibrator.vibrate(300);
                        break;
                    case AGAIN_SHAKE:
                        mActivity.mVibrator.vibrate(300);
                        break;
                    case END_SHAKE:
                        mActivity.isShake = false;//整体效果结束, 将震动设置为false
                        mActivity.createOneBet();//产生一注
                        break;
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void getHeaderInfo() {
        RetrofitBase.getRetrofit().create(GetCurrentIssueNoRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<GetCurrentIssueNoResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetCurrentIssueNoResponse>(this) {
                    @Override
                    protected void _onNext(final GetCurrentIssueNoResponse getCurrentIssueNoResponse) {
                        if (!Utils.isActivityRunning(OfficalLotteryDetailActivity.this)) {
                            return;
                        }
                        currentNo = getCurrentIssueNoResponse.getNo();


                        String year = Utils.toYear(System.currentTimeMillis());
                        if (getCurrentIssueNoResponse.getNo().startsWith(year)) {
                            issue.setText("距" + getCurrentIssueNoResponse.getNo().substring(4) + "期开奖");
                        } else {
                            issue.setText("距" + getCurrentIssueNoResponse.getNo() + "期开奖");
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case ChooseLotteryActivity.REPONSE_CODE:
                if (data != null) {
                    String code = data.getStringExtra("code");
                    int item_class = data.getIntExtra("item_class", -1);
                    if (!Utils.isEmpty(code) && item_class != -1) {
                        gotoLotteryDetailActivity(code, item_class);
                        finish();
                    }
                }
                break;
        }
    }


    public void gotoLotteryDetailActivity(String code, int index) {//0 其它 1官方2六合3传统
        switch (index) {
            case 1: {
                Intent intent = new Intent(OfficalLotteryDetailActivity.this, OfficalLotteryDetailActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
            case 2: {
                Intent intent = new Intent(OfficalLotteryDetailActivity.this, LiuhecaiDetailActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
            case 3: {
                Intent intent = new Intent(OfficalLotteryDetailActivity.this, ChuantongcaiActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
        }
    }


    /**
     * 获取运营商聊天室开关状态
     */
    public void getRoomStatus() {
        RetrofitBase.getRetrofit().create(GetChatRoomCurrentStatus.class).getResult()
                .compose(RxHelper.<ChatRoomStatus>handleResultReConnection())
                .subscribe(new RxSubscribe<ChatRoomStatus>(this) {
                    @Override
                    protected void _onNext(ChatRoomStatus chatRoomStatus) {
                        if (chatRoomStatus != null) {
                            ChatRoomStatus.DataBean data = chatRoomStatus.getData();
                            if (data != null) {
                                switch (data.getStatus()) {
                                    case ChatRoomStatus.CHAT_ROOM_STATUS_OPEN:
                                        ball_view.setVisibility(View.VISIBLE);
                                        break;
                                    case ChatRoomStatus.CHAT_ROOM_STATUS_CLOSE:
                                        ball_view.setVisibility(View.GONE);
                                        break;
                                }
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }
}